<template>
    <div class="app-role">
      <h3>限时秒杀</h3>
     <Query
       :items="queryColumns"
       :initial-params="queryParams"
       @query="handleQuery"
       labelWidth="100px"
     />
     <Table
       :table-columns="tableColumns"
       :table-loading="tableLoading"
       :table-data="tableData"
       :total="total"
       @pagination="handlePagination"
       :tree-props="{ children: 'children', hasChildren:'hasChildren',icon:'Plus' }"
     >
        <template v-slot:tools>
            <el-button-group>
                <el-button type="primary" @click="handleAdd()">添加活动</el-button>
            </el-button-group>
        </template>
       <template #status="{row}">
        <div>
          <span class="status-circle" :class="{
            greenStatus:row.status ==1,
            grayStatus:row.status !=1,
            }"></span>
          <span>{{ row.status==1?'未开始':row.status==2?'进行中':'已结束' }}</span>
        </div>
       </template>
       <template #opt="scope">
         <el-button type="primary" link @click="handleAdd(scope.row)">编辑</el-button>
         <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
       </template>
     </Table>
     <el-dialog v-model="showDialog" :title="dialogTitle" width="600">
        <el-row>
          <el-col :span="22">
            <el-form ref="refForm" :model="formData" :rules="formRules" size="default">
              <el-form-item label="活动名称" label-width="100px" >
                <el-input v-model="formData.title" placeholder="请输入活动名称"></el-input>
              </el-form-item>
              <el-form-item label="活动期限" label-width="100px" >
                <el-date-picker
                  v-model="formData.dateTime"
                  type="daterange"
                  unlink-panels
                  format="YYYY-MM-DD HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item label="秒杀商品" label-width="100px" >
                <div class="product_wrap">
                  <div>
                    <div v-if="formData.relateIdList && formData.relateIdList.length>0">
                      <span v-for="(item,i) in formData.relateIdList" :key="'relateIdList_'+i">
                        {{ item.productName }}
                        <span v-if="formData.relateIdList.length-1>i">，</span>
                      </span>
                    </div>
                    <el-button type="primary" size="default" @click="onOpen('other')">{{formData.relateIdList && formData.relateIdList.length>0?'更换商品':'选择商品'}}</el-button>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="限购次数" label-width="100px" >
                  <div style="width: 100%;"><el-radio v-model="formData.limitFlag" :value="2">不限制</el-radio></div>
                  <div>
                    <el-radio v-model="formData.limitFlag" :value="1">
                      活动期间每人最多购买<el-input-number v-model="formData.limitNum" :controls="false" style="width: 60px;margin: 0 8px;"></el-input-number>件
                    </el-radio>
                  </div>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showDialog = false" size="default">取消</el-button>
            <el-button type="primary" @click="handleSubmit" size="default">
              确定
            </el-button>
          </div>
        </template>
        <SeckillProduct :isCheckbox="true" type="2" :dialogVisible="dialogVisible" :idsList="productIds" @onOk="onOk" @onClose="dialogVisible = false"></SeckillProduct>
      </el-dialog>
    </div>
  </template>
  
  <script setup name="productTemeplate">
  import Table from "@/components/Table/index.vue";
  import Query from "@/components/Query/index.vue";
  import DialogForm from '@/components/FormDialog/index.vue'
  import SeckillProduct from '@/components/SeckillProduct'
  import { formatDate } from '@/utils'
  import { getSeckillList,saveSeckill,seckillAddList } from "@/api/activeMgmt";
  
  const { proxy } = getCurrentInstance()
  const tableData = ref([])
  const tableData2 = ref([])
  const total = ref(0)
  const total2 = ref(0)
  const tableLoading = ref(true)
  const tableLoading2 = ref(true)
  const dialogTitle = ref('')
  const loading = ref(false)
  const refForm = ref(null)
  const showDialog = ref(false)
  const router = useRouter();
  const skuList = ref([])
  const formData = ref({
  })
  const formRules = ref({
    
  })
  const detailId = ref(null)
  const detailData = ref({})
  
  const data = reactive({
   tableColumns: [
     { label: "活动名称",prop: "title"},
     { label: "活动商品",prop: "prodNames"},
     { label: "活动时间", prop: "gmtStart" },
     { label: "停止时间", prop: "gmtEnd" },
     { label: "活动状态", prop: "status",slot: 'status', },
     { label: "操作", fixed:'right', prop: "opt", slot: 'opt',width:120},
   ],
   queryColumns: [
    { label: "活动名称", prop: "title", type: 'input', attrs: {placeholder:'活动名称'}},
    { label: "活动商品", prop: "prodNames", type: 'input', attrs: {placeholder:'活动商品'}},
    { label: '活动状态', prop: 'contractStatus', type: 'select', options: [
      { label: "进行中", value: 1 },
      { label: "未开始", value: 2 },
      { label: "停止", value: 3 },
    ]},
    { label: "活动时间", prop: "overTime", type: 'datetime',attrs: { type: 'datetimerange',  endPlaceholder: '请选择', startPlaceholder: '请选择', valueFormat: 'YYYY-MM-DD HH:mm:ss', format: 'YYYY-MM-DD HH:mm:ss'},width:180},
   ],
   pageParams: {
    current: 1,
    size: 10
   },
   queryParams: {},
   formItems: [
  
   ]
  })
  const allLogisticList = ref([])// 物流公司
  const { tableColumns, queryColumns, pageParams, queryParams, formItems } = toRefs(data)
  const handleChange = (tab, event) => {
    queryParams.value.current = 1
    getList()
  }
  /** 获取列表数据 */
  const getList = () => {
    tableLoading.value = true
    const data  = {
      ...pageParams.value,
      ...queryParams.value,
    }
    getSeckillList(data)
    .then(res => {
      let list = res.data.records || []
       tableData.value = list
       total.value = res.data.total
    })
    .finally(() => {
       tableLoading.value = false
    })
  }
  
  getList()
  
  const openPage = (url)=>{
    window.open(url)
  }
  /** 搜索按钮操作 */
  const handleQuery = (val) => {
   queryParams.value = val
   getList()
  }
  /** 打开发货弹窗 */
  const handleAdd = (row) => {
    dialogTitle.value = row?'编辑':'新增'
    if(row){
      formData.value = {
        ...row,
        dateTime:[row.gmtStart,row.gmtEnd]
      }
    }else{
      formData.value = {
        title:'',
        dateTime:null,
        limitFlag:2,
        limitNum:0,
        relateIdList:[],

      }
    }
    detailId.value = row?.id || ''
    showDialog.value = true
  }
  /** 删除按钮操作 */
  function handleDelete(row) {
    proxy.$modal.confirm('是否确认删除此数据？').then(function() {
      saveSeckill({id: row.id, delFlag: -1}).then(() => {
        getList()
        proxy.$modal.msgSuccess("删除成功")
      })
    })
  }
  const handlePagination = (val) => {
   pageParams.value = val
   getList()
  }
  
  const handleSubmit = ()=>{
    refForm.value.validate(valid => {
      if (!valid) return
      let dateTime = formData.value.dateTime || []
      let params = {
        ...formData.value,
        gmtStart:dateTime[0]&&formatDate(dateTime[0]),
        gmtEnd:dateTime[1]&&formatDate(dateTime[1]),
        id:detailId.value || null,
      }
      saveSeckill(params).then(res=>{
        showDialog.value = false
        proxy.$modal.msgSuccess("保存成功")
        pageParams.value.current = 1
        getList()
      })
    })
  }
  const dialogVisible = ref(false)
  const isCheckbox = ref(false)
  const openType = ref('')
  const productIds = ref([])
const onOpen = (type) => {
  let data = formData.value
  let arr = []
  isCheckbox.value = true
  arr = formData.value.relateIdList || []
  productIds.value = arr || []
  openType.value = type
  dialogVisible.value = true
}
const onOk = (data) => {
  let type = openType.value
  if(type=='other'){
    let prodArr = JSON.parse(JSON.stringify(formData.value.relateIdList || []))
    let arr2 = prodArr.filter(item=>item.id)
    let arr = []
    if(arr2.length>0){
      let prodIdList = []
      arr2.map(item => {
        let flag = false
        prodIdList.push(item.prodId)
        data.value.forEach(item2 => {
          if(item2.id==item.prodId){
            flag = true
            item.sortNum = item2.sortNum
          }
        })
        if(flag){
        //   arr.push({
        //     ...item,
        //     delFlag:-1,
        //   })
        // }else{
          arr.push({
            ...item,
            delFlag:0,
          })
        }
      })
      data.value.forEach(item => {
        if(!prodIdList.includes(item.id)){
          arr.push(
            {
              "delFlag": 0,
              "gmtCreate": "",
              "gmtModify": "",
              "id": null,
              "prodId": item.id,
              "sortNum": item.sortNum,
              productName:item.productName
            }
          )
        }
      });
    }else{
      data.value.forEach(item => {
        arr.push(
          {
            "delFlag": 0,
            "gmtCreate": "",
            "gmtModify": "",
            "id": null,
            "prodId": item.id,
            "sortNum": item.sortNum,
            productName:item.productName
          }
        )
      });
    }
    formData.value.relateIdList = arr
  }else{
    if(type=='oneId'){
      formData.value.oneId = data.value[0]?.id
      formData.value.oneProductName = data.value[0]?.productName
    }
    if(type=='twoId'){
      formData.value.twoId = data.value[0]?.id
      formData.value.twoProductName = data.value[0]?.productName
    }
    if(type=='threeId'){
      formData.value.threeId = data.value[0]?.id
      formData.value.threeProductName = data.value[0]?.productName
    }
    if(type=='fourId'){
      formData.value.fourId = data.value[0]?.id
      formData.value.fourProductName = data.value[0]?.productName
    }
  }
  // formData.value.typeIdList = data.value
  dialogVisible.value = false
}
  </script>
  
  <style lang="scss" scoped>
  .productName_box{
    display: flex;
    align-items: center;
    .productName_img{
      width: 80px;
      height: 80px;
      object-fit: contain;
      margin-right: 8px;
    }
    span{
  
    }
  }
  .app-role {
   padding: 8px
  }
  .product_tem_wrap{
    display: flex;
    width: 100%;
    max-height: 400px;
    overflow: auto;
    flex-wrap: wrap;
    padding: 20px 0;
    padding-left:20px;
  }
  .product_tem_box{
    border: 1px solid #ddd;
    border-radius: 2px;
    cursor: pointer;
    height: 90px;
    margin-bottom: 20px;
    margin-right: 3%;
    padding: 10px;
    width: 30%;
    display: flex;
    .product_tem_img{
      width: 68px;
      height: 68px;
      margin-right: 8px;
      img{
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
    .product_tem_name{
      flex: 1;
    }
    .product_tem_name_text{
      height: 40px;
      line-height: 20px;
      margin-bottom: 6px;
      max-width: 150px;
      -webkit-box-orient: vertical;
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal !important;
      word-break: break-all;
    }
    .product_tem_typeName{
      color: #c4c4c3;
    }
  }
  .product_tem_box:hover{
    border-color: #4a89f0;
  }
  .product_wrap{
    width: 90%;
    display: flex;
    .product_box{
      margin-right: 10px;
      flex: 1;
    }
    .product_img_box{
      width: 200px;
    }
  }
  :deep(.sku-img-wrap) {
    cursor: pointer;
    .el-upload--picture-card,.el-upload-list--picture-card .el-upload-list__item-actions,.el-upload-list--picture-card .el-upload-list__item{
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80px;
      height: 80px;
    }
    img{
      width: 80px;
      height: 80px;
      object-fit: contain;
      cursor: pointer;
    }
  }
  </style>